package com.qkst.website.backstage.init;

import java.util.Enumeration;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.qkst.website.common.utils.PropertiesUtils;

/***
 * @author lihao
 * @emial ahlxlihao@163.com
 * @description 启动服务时用于加载配置文件内容，读入内存中
 * @version 1.0v
 * @date 2017-04-26
 */
public class SysconfRegistry implements ApplicationListener<ContextRefreshedEvent> {
	
	private static final Logger log = LoggerFactory.getLogger(SysconfRegistry.class);
	private static SysconfRegistry instance = null;
	public final static ConcurrentHashMap<String, String> CONCURRENT_MAP = new ConcurrentHashMap<String, String>();

	public static SysconfRegistry getInstance(){
		if(instance == null){
			initializeRegistry();
		}
		return instance;
	}
	
	
	private static synchronized void initializeRegistry(){      
        try {
            if(instance == null){
            	instance = new SysconfRegistry();
            	instance.initialize();
            }	         
        } catch(Exception e){
        	e.printStackTrace();
        }
    }
	
	public void  initialize() throws Exception {
		instance = this;
	}
	
	public void  refresh() throws Exception {
		CONCURRENT_MAP.clear();
		Properties properties=PropertiesUtils.readProperties(null,"sysconf.properties");
		Enumeration<?> enu=properties.propertyNames();
		while(enu.hasMoreElements()){
		    String key = (String)enu.nextElement();
		    String value=properties.getProperty(key);
		    if (key != null) {
				value = ((value == null) ? "" : value);
				CONCURRENT_MAP.put(key, value);
			}
		} 
		log.info("系统参数刷新完成 !");
	}
	
	public String getString(String key) {
		String value = null;
		if (CONCURRENT_MAP.containsKey(key)) {
			value = (String) CONCURRENT_MAP.get(key);
		}
		return value;
	}
	
	public void onApplicationEvent(ContextRefreshedEvent event) {
			if(event.getApplicationContext().getParent()!=null){
				try {
					refresh();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
	}

}
